package https

import (
	"api_online/data"
	"api_online/helpers"
	"html/template"
	"net/http"
	"strings"
)

// 首页
func Index(w http.ResponseWriter, r *http.Request) {
	tem, err := template.ParseFiles("./view/index.html")
	if err != nil {
		panic("模板加载失败")
	}
	tem.Execute(w, nil)
}

// 表单请求页面
func Request(w http.ResponseWriter, r *http.Request) {
	tem, err := template.ParseFiles("./view/request.html")
	if err != nil {
		panic("模板加载失败")
	}

	tem.Execute(w, nil)
}

type resultStruct struct {
	Result string
	UrlStr string
}

// 处理在线请求返回值
func Result(w http.ResponseWriter, r *http.Request) {
	url := r.PostFormValue("_url")
	urlFull := r.PostFormValue("_urlfull")
	method := strings.ToLower(r.PostFormValue("_method"))
	param := r.PostForm

	// 缓存参数
	data.Cache.AddParamByUrl(url, param)

	// 缓存结果
	data.Cache.AddResultCacheKeyByUrl(url, "code", "返回码")
	data.Cache.AddResultCacheKeyByUrl(url, "message", "返回消息")
	data.Cache.AddResultCacheKeyByUrl(url, "data", "返回数据")

	// 发起请求
	result := resultStruct{
		UrlStr: url,
	}

	if method == "get" {
		// get 提交
		res, err := helpers.Get(urlFull, param)
		if err != nil {
			panic(err)
		}
		result.Result = res
	} else {
		// post 提交
		res, err := helpers.Post(urlFull, param)
		if err != nil {
			panic(err)
		}
		result.Result = res
	}

	tem, err := template.ParseFiles("./view/result.html")
	if err != nil {
		panic(err)
	}

	_ = tem.Execute(w, result)
}